package com.quectel.cms.controller.securitypatrol;


import cn.hutool.core.lang.func.LambdaUtil;
import com.quectel.cms.controller.BaseController;
import com.quectel.constant.global.SystemConstants;
import com.quectel.constant.global.annotation.RequirePermissions;
import com.quectel.core.module.device.dto.DeviceDto;
import com.quectel.core.module.device.service.DeviceService;
import com.quectel.core.module.securitypatrol.dto.SecurityPatrolDeviceSubjectDto;
import com.quectel.core.module.securitypatrol.dto.SecurityPatrolRouteDto;
import com.quectel.core.module.securitypatrol.service.SecurityPatrolDeviceSubjectService;
import com.quectel.core.module.securitypatrol.service.SecurityPatrolRouteService;
import com.quectel.util.common.JacksonUtils;
import com.quectel.util.common.Page;
import com.quectel.util.common.Request;
import com.quectel.util.common.Response;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author caolu
 * @email louis.cao@quectel.com
 * @date 2022/05/07 14:10
 */
@RestController
@RequestMapping("securityPatrolRoute")
@Tag(name = "SecurityPatrolRouteController", description = "安保巡逻路线相关api")
public class SecurityPatrolRouteController extends BaseController {

    @DubboReference
    private SecurityPatrolRouteService securityPatrolRouteService;
    @DubboReference
    private SecurityPatrolDeviceSubjectService securityPatrolDeviceSubjectService;
    @DubboReference
    private DeviceService deviceService;

    /**
     * 查询可选择的安保巡逻路线
     */
    @GetMapping("canSelectedRoutes")
    @Operation(summary = "查询可选择的安保巡逻路线")
    public Response<List<SecurityPatrolRouteDto>> canSelectedRoutes(@RequestParam Map<String, Object> params) {
        //查询列表数据
        super.fillAuthorityData(params);

        return Response.<List<SecurityPatrolRouteDto>>ok().wrap(securityPatrolRouteService.queryList(params));
    }

    /**
     * 安保巡逻路线分页查询列表
     */
    @GetMapping("list")
    @RequirePermissions(values = "securityPatrolRoute:list")
    @Operation(summary = "安保巡逻路线分页查询列表")
    public Response<Page<SecurityPatrolRouteDto>> list(
            @Parameter(description = "从1开始的页码数") @RequestParam Integer pageNo,
            @Parameter(description = "每页多少条") @RequestParam Integer pageSize
    ) {
        //查询列表数据
        Request request = Request.configParams(Request.parseParams(httpServletRequest));

        super.fillAuthorityData(request.getParams());
        int total = securityPatrolRouteService.queryTotal(request.getParams());

        List<SecurityPatrolRouteDto> list = null;
        if (total > 0) {
            list = securityPatrolRouteService.queryList(request.getParams());
        } else {
            list = new ArrayList<>();
        }

        Page<SecurityPatrolRouteDto> page = new Page<>(request.getPageNo(), request.getPageSize(), total, list);
        return Response.<Page<SecurityPatrolRouteDto>>ok().wrap(page);
    }


    /**
     * 根据id查询安保巡逻路线记录，用于编辑反显
     */
    @GetMapping("infoForEdit/{id}")
    @RequirePermissions(values = "securityPatrolRoute:edit")
    @Operation(summary = "根据id查询安保巡逻路线记录，用于编辑反显")
    public Response<SecurityPatrolRouteDto> infoForEdit(@PathVariable("id") Long id) {

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);
        params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(id));
        if (securityPatrolRouteService.queryTotal(params) <= 0) {
            return Response.error(SystemConstants.ILLEGAL_MSG);
        }

        SecurityPatrolRouteDto securityPatrolRouteDto = securityPatrolRouteService.selectById(id);

        return Response.<SecurityPatrolRouteDto>ok().wrap((securityPatrolRouteDto));
    }

    /**
     * 根据id查询安保巡逻路线记录
     */
    @GetMapping("info/{id}")
    @RequirePermissions(values = "securityPatrolRoute:info")
    @Operation(summary = "根据id查询安保巡逻路线记录")
    public Response<SecurityPatrolRouteDto> info(@PathVariable("id") Long id) {

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);
        params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(id));
        if (securityPatrolRouteService.queryTotal(params) <= 0) {
            return Response.error(SystemConstants.ILLEGAL_MSG);
        }

        SecurityPatrolRouteDto securityPatrolRouteDto = securityPatrolRouteService.selectById(id);

        return Response.<SecurityPatrolRouteDto>ok().wrap((securityPatrolRouteDto));
    }

    /**
     * 保存安保巡逻路线记录
     */
    @PostMapping("save")
    @RequirePermissions(values = "securityPatrolRoute:edit")
    @Operation(summary = "保存安保巡逻路线记录")
    public Response<Object> save(@RequestBody @Validated SecurityPatrolRouteDto securityPatrolRouteDto) {
        Map<String, Object> params = new HashMap<>();
        //填充基础数据
        fillSaveCommonData(securityPatrolRouteDto);

        // 判断点位数组是否绑定项目,提示
        List<String> noneBindSubjectDeviceList = new ArrayList<>();
        if (StringUtils.hasLength(securityPatrolRouteDto.getRouteArr())) {
            List<String> deviceIds = JacksonUtils.parseArray(securityPatrolRouteDto.getRouteArr(), String.class);
            for (int i = 0; i < deviceIds.size(); i++) {
                params.clear();
                params.put(LambdaUtil.getFieldName(SecurityPatrolDeviceSubjectDto::getDeviceId), deviceIds.get(i));
                int queryTotal = securityPatrolDeviceSubjectService.queryTotal(params);
                if (queryTotal <= 0) {
                    noneBindSubjectDeviceList.add(deviceService.selectCacheById(Long.valueOf(deviceIds.get(i))).getName());
                }
            }
            // 如果noneBindSubjectDeviceList.size > 0 说明有问题，不给保存
            if (noneBindSubjectDeviceList.size() > 0) {
                StringBuilder builder = new StringBuilder();
                for (String deviceName : noneBindSubjectDeviceList) {
                    builder.append(deviceName).append(",");
                }
                builder.append("没有绑定项目");
                return Response.error(builder.toString());
            }
        }
        securityPatrolRouteService.save(securityPatrolRouteDto);

        return Response.ok();
    }

    /**
     * 修改安保巡逻路线记录
     */
    @PostMapping("update")
    @RequirePermissions(values = "securityPatrolRoute:edit")
    @Operation(summary = "修改安保巡逻路线记录")
    public Response<Object> update(@RequestBody @Validated SecurityPatrolRouteDto securityPatrolRouteDto) {

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);
        params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(securityPatrolRouteDto.getId()));
        if (securityPatrolRouteService.queryTotal(params) <= 0) {
            return Response.error(SystemConstants.ILLEGAL_MSG);
        }
        //填充基础数据
        fillEditCommonData(securityPatrolRouteDto);
        // 判断点位数组是否绑定项目,提示
        List<String> noneBindSubjectDeviceList = new ArrayList<>();
        if (StringUtils.hasLength(securityPatrolRouteDto.getRouteArr())) {
            List<String> deviceIds = JacksonUtils.parseArray(securityPatrolRouteDto.getRouteArr(), String.class);
            for (int i = 0; i < deviceIds.size(); i++) {
                params.clear();
                params.put(LambdaUtil.getFieldName(SecurityPatrolDeviceSubjectDto::getDeviceId), deviceIds.get(i));
                int queryTotal = securityPatrolDeviceSubjectService.queryTotal(params);
                if (queryTotal <= 0) {
                    DeviceDto deviceDto = deviceService.selectById(Long.valueOf(deviceIds.get(i)));
                    Assert.state(deviceDto != null, "此设备id数据已被删除，设备id：" + deviceIds.get(i));
                    noneBindSubjectDeviceList.add(deviceDto.getName());
                }
            }
            // 如果noneBindSubjectDeviceList.size > 0 说明有问题，不给保存
            if (noneBindSubjectDeviceList.size() > 0) {
                StringBuilder builder = new StringBuilder();
                for (String deviceName : noneBindSubjectDeviceList) {
                    builder.append(deviceName).append(",");
                }
                builder.append("没有绑定项目");
                return Response.error(builder.toString());
            }
        }

        securityPatrolRouteService.updateById(securityPatrolRouteDto);

        return Response.ok();
    }

    /**
     * 批量删除安保巡逻路线记录
     */
    @PostMapping("delete")
    @RequirePermissions(values = "securityPatrolRoute:delete")
    @Operation(summary = "批量删除安保巡逻路线记录")
    public Response<Object> delete(@RequestBody Long[] ids) {

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);

        for (Long id : ids) {

            params.remove(SystemConstants.ENTITY_ID_FLAG);
            params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(id));

            if (securityPatrolRouteService.queryTotal(params) <= 0) {
                return Response.error(SystemConstants.ILLEGAL_MSG);
            }
        }

        securityPatrolRouteService.deleteBatch(ids);

        return Response.ok();
    }
}
